package co.baiku.boot;

import co.baiku.boot.common.tools.JsonTools;
import co.baiku.boot.config.BaijiaLiveConfig;
import co.baiku.boot.live.baijiayun.HttpKit;
import co.baiku.boot.live.baijiayun.message.BaiJiaLiveApiMessage;
import co.baiku.boot.live.baijiayun.model.BaiJiaPlaybackBasicInfo;
import co.baiku.boot.live.baijiayun.model.BaiJiaRoomInfo;
import co.baiku.boot.live.baijiayun.request.BaiJiaCreatekeyRequest;
import co.baiku.boot.live.baijiayun.request.BaiJiaLiveRequest;
import co.baiku.boot.live.baijiayun.request.BaiJiaRoomCreateRequest;
import co.baiku.boot.live.baijiayun.request.BaiJiaRoomUpdateRequest;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 百家云直播接口
 */
@Component
@ConditionalOnProperty("ajavaer.live.baijiayun.partner_id")
public class BaiJiaLive implements InitializingBean {
    private Logger log = LoggerFactory.getLogger(BaiJiaLive.class);
    @Resource
    private BaijiaLiveConfig baijiaLiveConfig;
    @Resource
    private Environment environment;

    private Boolean isDebug = true;


    /**
     * 获取/重置partner_key
     */
    public BaiJiaLiveApiMessage<Map> createkey(BaiJiaCreatekeyRequest request) {
        return doPost("partner/createkey", request, new TypeReference<BaiJiaLiveApiMessage<Map>>() {
        });
    }

    /**
     * 创建房间
     */
    public BaiJiaLiveApiMessage<BaiJiaRoomInfo> roomCreate(BaiJiaRoomCreateRequest request) {
        return doPost("room/create", request, new TypeReference<BaiJiaLiveApiMessage<BaiJiaRoomInfo>>() {
        });
    }

    /**
     * 删除房间
     */
    public BaiJiaLiveApiMessage roomDelete(Long roomId) {
        return doPost("room/delete", new BaiJiaLiveRequest() {
            @Override
            protected Map<String, Object> buildMap() {
                Map<String, Object> request = new HashMap<>(16);
                request.put("room_id", roomId);
                return request;
            }
        }, new TypeReference<BaiJiaLiveApiMessage<BaiJiaRoomInfo>>() {
        });
    }

    /**
     * 更新房间
     */
    public BaiJiaLiveApiMessage roomUpdate(BaiJiaRoomUpdateRequest request) {
        return doPost("room/update", request, new TypeReference<BaiJiaLiveApiMessage<BaiJiaRoomInfo>>() {
        });
    }

    /**
     * 设置直播上下课事件回调地址
     */
    public BaiJiaLiveApiMessage<Map> setClassCallbackUrl(String url) {
        return doPost("live_account/setClassCallbackUrl", new BaiJiaLiveRequest() {
            @Override
            protected Map<String, Object> buildMap() {
                Map<String, Object> request = new HashMap<>(16);
                request.put("url", url);
                return request;
            }
        }, new TypeReference<BaiJiaLiveApiMessage<Map>>() {
        });
    }


    /**
     * 设置视频回放转码回调地址
     */
    public BaiJiaLiveApiMessage<Map> setTranscodeCallbackUrl(String url) {
        return doPost("video_account/setTranscodeCallbackUrl", new BaiJiaLiveRequest() {
            @Override
            protected Map<String, Object> buildMap() {
                Map<String, Object> request = new HashMap<>(16);
                request.put("url", url);
                return request;
            }
        }, new TypeReference<BaiJiaLiveApiMessage<Map>>() {
        });
    }

    /**
     * 查询直播回放信息
     *
     * @param roomId 房间号
     */
    public BaiJiaLiveApiMessage<BaiJiaPlaybackBasicInfo> playbackGetBasicInfo(Long roomId) {
        return doPost("playback/getBasicInfo", new BaiJiaLiveRequest() {
            @Override
            protected Map<String, Object> buildMap() {
                Map<String, Object> request = new HashMap<>(16);
                request.put("room_id", roomId);
                return request;
            }
        }, new TypeReference<BaiJiaLiveApiMessage<BaiJiaPlaybackBasicInfo>>() {
        });
    }

    /**
     * 获取回放token
     *
     * @param roomId 房间id
     * @return
     */
    public BaiJiaLiveApiMessage<Map> playbackGetPlayerToken(Long roomId) {
        return doPost("playback/getPlayerToken", new BaiJiaLiveRequest() {
            @Override
            protected Map<String, Object> buildMap() {
                Map<String, Object> request = new HashMap<>(16);
                request.put("room_id", roomId);
                return request;
            }
        }, new TypeReference<BaiJiaLiveApiMessage<Map>>() {
        });
    }


    /**
     * 集中请求处理
     */
    private <T> T doPost(String path, BaiJiaLiveRequest request, TypeReference<T> type) {
        String url = this.baijiaLiveConfig.getHost() + "/openapi/" + path;
        String params = toFormParam(request.toMap(baijiaLiveConfig));
        if (isDebug) {
            log.debug("[baiJia live] doPost request:" + params);
        }
        return JsonTools.jsonToBean(HttpKit.post(url, params), type);
    }


    private String toFormParam(Map<String, Object> toMap) {
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : toMap.entrySet()) {
            if (entry.getValue() == null) {
                continue;
            }
            builder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        return builder.substring(0, builder.length() - 1);
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        this.isDebug = this.environment.getProperty("ajavaer.debug", Boolean.class, true);
        if (isDebug) {
            log.debug("Live BaiJiaLive init");
        }
    }
}
